package com.xncoding.valid.Converter;

import com.xncoding.valid.dto.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

public class CustomHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    private static Logger logger = LoggerFactory.getLogger(CustomHttpMessageConverter.class) ;

    // 这里指明了只要接收参数是Users类型的都能进行转换
    @Override
    protected boolean supports(Class<?> clazz) {
        return Users.class == clazz ;
    }
    // 读取内容进行内容的转换
    @Override
    protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        String content = inToString(inputMessage.getBody()) ;
        String[] keys = content.split(",") ;
        Users instance = null ;
        try {
            instance = (Users) clazz.newInstance();
        } catch (Exception e1) {
            e1.printStackTrace() ;
        }
        for (String key : keys) {
            String[] vk = key.split(":") ;
            try {
                Field[] fields = clazz.getDeclaredFields() ;
                for (Field f:fields) {
                    if (f.getName().equals(vk[0])) {
                        f.setAccessible(true) ;
                        Class<?> type = f.getType() ;
                        if (String.class == type) {
                            f.set(instance, vk[1]) ;
                        } else if (Integer.class == type) {
                            f.set(instance, Integer.parseInt(vk[1])) ;
                        }
                        break ;
                    }
                }
            } catch (Exception e) {
                logger.error("错误：{}", e) ;
            }
        }
        return instance ;
    }

    // 如果将返回值以什么形式输出，这里就是调用了对象的toString方法。
    @Override
    protected void writeInternal(Object t, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        outputMessage.getBody().write(t.toString().getBytes()) ;
    }

    @Override
    protected boolean canWrite(MediaType mediaType) {
        if (mediaType == null || MediaType.ALL.equals(mediaType)) {
            return true;
        }
        for (MediaType supportedMediaType : getSupportedMediaTypes()) {
            if (supportedMediaType.isCompatibleWith(mediaType)) {
                return true;
            }
        }
        return false;
    }

    private String inToString(InputStream is) {
        byte[] buf = new byte[10 * 1024] ;
        int leng = -1 ;
        StringBuilder sb = new StringBuilder() ;
        try {
            while ((leng = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, leng)) ;
            }
            return sb.toString() ;
        } catch (IOException e) {
            throw new RuntimeException(e) ;
        }
    }

}
